var DBFactory = require('../db/mysql_db');
var purchaseDao = module.exports;

purchaseDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var purchase = {};
    ['id', 'name', 'price', 'duration', 'lvl', 'multi_rate', 'status'].forEach(function(p) {
        if(data[p]) purchase[p] = data[p];
    })
    var sql = 'replace into purchase_item set ? ';
    DBFactory.executeSql(sql, purchase, 'purchaseSave', function(err, result) {
        if(err) return cb(err);
        cb(null, 'success！');
    })
}

purchaseDao.list = function(data, cb) {
    var sql = 'select * from purchase_item where 1 ';
    var sqlTotal = 'select count(*) as count from purchase_item where 1 ';
    var arr = [];
    if(data.status) {
        sql += ' and status = ? ';
        sqlTotal += ' and status = ? ';
        arr.push(data.status);
    } else {
        sql += ' and status = 1 ';
        sqlTotal += ' and status = 1 ';
    }
    sql += ' order by created_date desc ';
    DBFactory.executeSql(sqlTotal, arr, 'purchaseListTotal', function(err, total) {
        if(err) return cb(err);
        if(total[0].count == 0) return cb(null, {total:0});
        sql += ' limit ? , ? ';
        arr.push(data.start);
        arr.push(data.size);
        DBFactory.executeSql(sql, arr, 'purchaseList', function(e, result) {
            if(e) return cb(e);
            cb(null, {total: total[0].count, data: result});
        })
    })
}

purchaseDao.updateStatus = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'update purchase_item set status = ? where id = ? ';
    DBFactory.executeSql(sql, [data.status, data.id], 'purchaseUpdateStatus', function(err, result) {
        if(err) return cb(err);
        cb(null, 'success!');
    })
}

purchaseDao.receivables = function(data, cb) {
    var sql = 'select * from purchase_log where 1 ';
    var sqlTotal = 'select count(*) as count from purchase_log where 1 ';
    var arr = [];
    if(data.type) {
        sql += ' and type = ? ';
        sqlTotal += ' and type = ? ';
        arr.push(data.type);
    }
    sql += ' order by created_date desc ';
    DBFactory.executeSql(sqlTotal, arr, 'receivablesTotal', function(err, total) {
        if(err) return cb(err);
        if(total[0].count == 0) return cb(null, {total:0});
        sql += ' limit ? , ? ';
        arr.push(data.start);
        arr.push(data.size);
        DBFactory.executeSql(sql, arr, 'receivablesList', function(e, result) {
            if(e) return cb(e);
            cb(null, {total: total[0].count, data: result});
        })
    })
}

purchaseDao.getPurchaseInfo = function(data, cb) {
    var sql = 'select * from purchase_item where id = ? and status = 1 ';
    DBFactory.executeSql(sql, [data.id], 'getPurchaseInfo', function(e, result) {
        if(e) return cb(e);
        cb(null, result);
    })
}